package model

import (
	"fmt"
	"go.uber.org/zap"
	"mall-portalv2/global"
	"mall-portalv2/library/utils"
	"strings"
	"time"
)

// OmsOrder 订单表
type OmsOrder struct {
	ID                int64     `json:"id" gorm:"id"` // 订单id
	MemberId          int64     `json:"memberId" gorm:"member_id"`
	CouponId          int64     `json:"couponId" gorm:"coupon_id"`
	OrderSn           string    `json:"orderSn" gorm:"order_sn"`                      // 订单编号
	CreateTime        time.Time `json:"createTime" gorm:"create_time"`                // 提交时间
	MemberUsername    string    `json:"memberUsername" gorm:"member_username"`        // 用户帐号
	TotalAmount       float64   `json:"totalAmount" gorm:"total_amount"`              // 订单总金额
	PayAmount         float64   `json:"payAmount" gorm:"pay_amount"`                  // 应付金额（实际支付金额）
	FreightAmount     float64   `json:"freightAmount" gorm:"freight_amount"`          // 运费金额
	PromotionAmount   float64   `json:"promotionAmount" gorm:"promotion_amount"`      // 促销优化金额（促销价、满减、阶梯价）
	IntegrationAmount float64   `json:"integrationAmount" gorm:"integration_amount"`  // 积分抵扣金额
	CouponAmount      float64   `json:"couponAmount" gorm:"coupon_amount"`            // 优惠券抵扣金额
	DiscountAmount    float64   `json:"discountAmount" gorm:"discount_amount"`        // 管理员后台调整订单使用的折扣金额
	PayType           int64     `json:"payType" gorm:"pay_type"`                      // 支付方式：0->未支付；1->支付宝；2->微信；3->paypal
	SourceType        int64     `json:"sourceType" gorm:"source_type"`                // 订单来源：0->PC订单；1->app订单
	Status            int64     `json:"status" gorm:"status"`                         // 订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
	OrderType         int64     `json:"orderType" gorm:"order_type"`                  // 订单类型：0->正常订单；1->秒杀订单
	DeliveryCompany   string    `json:"deliveryCompany" gorm:"delivery_company"`      // 物流公司(配送方式)
	DeliverySn        string    `json:"deliverySn" gorm:"delivery_sn"`                // 物流单号
	AutoConfirmDay    int64     `json:"autoConfirmDay" gorm:"auto_confirm_day"`       // 自动确认时间（天）
	Integration       int64     `json:"integration" gorm:"integration"`               // 可以获得的积分
	Growth            int64     `json:"growth" gorm:"growth"`                         // 可以活动的成长值
	PromotionInfo     string    `json:"promotionInfo" gorm:"promotion_info"`          // 活动信息
	BillType          int64     `json:"billType" gorm:"bill_type"`                    // 发票类型：0->不开发票；1->电子发票；2->纸质发票
	BillHeader        string    `json:"billHeader" gorm:"bill_header"`                // 发票抬头
	BillContent       string    `json:"billContent" gorm:"bill_content"`              // 发票内容
	BillReceiverPhone string    `json:"billReceiverPhone" gorm:"bill_receiver_phone"` // 收票人电话
	BillReceiverEmail string    `json:"billReceiverEmail" gorm:"bill_receiver_email"` // 收票人邮箱

	ReceiverID            int64  `json:"receiverID" gorm:"receiver_id"`                        // 收货人地址的ID
	ReceiverName          string `json:"receiverName" gorm:"receiver_name"`                    // 收货人姓名
	ReceiverPhone         string `json:"receiverPhone" gorm:"receiver_phone"`                  // 收货人电话
	ReceiverPostCode      string `json:"receiverPostCode" gorm:"receiver_post_code"`           // 收货人邮编
	ReceiverProvince      string `json:"receiverProvince" gorm:"receiver_province"`            // 省份/直辖市
	ReceiverCity          string `json:"receiverCity" gorm:"receiver_city"`                    // 城市
	ReceiverRegion        string `json:"receiverRegion" gorm:"receiver_region"`                // 区
	ReceiverDetailAddress string `json:"receiverDetailAddress" gorm:"receiver_detail_address"` // 详细地址
	Note                  string `json:"note" gorm:"note"`                                     // 订单备注

	ConfirmStatus  int64      `json:"confirmStatus" gorm:"confirm_status"`   // 确认收货状态：0->未确认；1->已确认
	DeleteStatus   int64      `json:"deleteStatus" gorm:"delete_status"`     // 删除状态：0->未删除；1->已删除
	UseIntegration int64      `json:"useIntegration" gorm:"use_integration"` // 下单时使用的积分
	PaymentTime    *time.Time `json:"paymentTime" gorm:"payment_time"`       // 支付时间
	// 支付返回的数据
	PaymentData     string     `json:"-"  gorm:"payment_data"`
	DeadlinePayment *time.Time `json:"deadlinePayment" json:"deadline_payment"` // 支付倒计时时间
	DeliveryTime    *time.Time `json:"deliveryTime" gorm:"delivery_time"`       // 发货时间
	DeliveryDate    *time.Time `json:"deliveryDate" gorm:"delivery_date"`       // 预估发货时间
	ReceiveTime     *time.Time `json:"receiveTime" gorm:"receive_time"`         // 确认收货时间
	CommentTime     *time.Time `json:"commentTime" gorm:"comment_time"`         // 评价时间
	ModifyTime      *time.Time `json:"modifyTime" gorm:"modify_time"`           // 修改时间
	MemberCom       int        `json:"memberCom" gorm:"member_com"`             // 用户标识（0 -> 未读， 1 -> 已读）
}

// TableName 表名称
func (*OmsOrder) TableName() string {
	return "oms_order"
}

type OrderList struct {
	OrderItemList []OmsOrderItemAndProduct `json:"orderItemList"`

	ID                int64     `json:"id" gorm:"id"` // 订单id
	MemberId          int64     `json:"memberId" gorm:"member_id"`
	CouponId          int64     `json:"couponId" gorm:"coupon_id"`
	OrderSn           string    `json:"orderSn" gorm:"order_sn"`                      // 订单编号
	CreateTime        time.Time `json:"createTime" gorm:"create_time"`                // 提交时间
	MemberUsername    string    `json:"memberUsername" gorm:"member_username"`        // 用户帐号
	TotalAmount       float64   `json:"totalAmount" gorm:"total_amount"`              // 订单总金额
	PayAmount         float64   `json:"payAmount" gorm:"pay_amount"`                  // 应付金额（实际支付金额）
	FreightAmount     float64   `json:"freightAmount" gorm:"freight_amount"`          // 运费金额
	PromotionAmount   float64   `json:"promotionAmount" gorm:"promotion_amount"`      // 促销优化金额（促销价、满减、阶梯价）
	IntegrationAmount float64   `json:"integrationAmount" gorm:"integration_amount"`  // 积分抵扣金额
	CouponAmount      float64   `json:"couponAmount" gorm:"coupon_amount"`            // 优惠券抵扣金额
	DiscountAmount    float64   `json:"discountAmount" gorm:"discount_amount"`        // 管理员后台调整订单使用的折扣金额
	PayType           int64     `json:"payType" gorm:"pay_type"`                      // 支付方式：0->未支付；1->支付宝；2->微信；3->paypal
	SourceType        int64     `json:"sourceType" gorm:"source_type"`                // 订单来源：0->PC订单；1->app订单
	Status            int64     `json:"status" gorm:"status"`                         // 订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
	OrderType         int64     `json:"orderType" gorm:"order_type"`                  // 订单类型：0->正常订单；1->秒杀订单
	DeliveryCompany   string    `json:"deliveryCompany" gorm:"delivery_company"`      // 物流公司(配送方式)
	DeliverySn        string    `json:"deliverySn" gorm:"delivery_sn"`                // 物流单号
	AutoConfirmDay    int64     `json:"autoConfirmDay" gorm:"auto_confirm_day"`       // 自动确认时间（天）
	Integration       int64     `json:"integration" gorm:"integration"`               // 可以获得的积分
	Growth            int64     `json:"growth" gorm:"growth"`                         // 可以活动的成长值
	PromotionInfo     string    `json:"promotionInfo" gorm:"promotion_info"`          // 活动信息
	BillType          int64     `json:"billType" gorm:"bill_type"`                    // 发票类型：0->不开发票；1->电子发票；2->纸质发票
	BillHeader        string    `json:"billHeader" gorm:"bill_header"`                // 发票抬头
	BillContent       string    `json:"billContent" gorm:"bill_content"`              // 发票内容
	BillReceiverPhone string    `json:"billReceiverPhone" gorm:"bill_receiver_phone"` // 收票人电话
	BillReceiverEmail string    `json:"billReceiverEmail" gorm:"bill_receiver_email"` // 收票人邮箱

	ReceiverID            int64  `json:"receiverID" gorm:"receiver_id"`                        // 收货人地址的ID
	ReceiverName          string `json:"receiverName" gorm:"receiver_name"`                    // 收货人姓名
	ReceiverPhone         string `json:"receiverPhone" gorm:"receiver_phone"`                  // 收货人电话
	ReceiverPostCode      string `json:"receiverPostCode" gorm:"receiver_post_code"`           // 收货人邮编
	ReceiverProvince      string `json:"receiverProvince" gorm:"receiver_province"`            // 省份/直辖市
	ReceiverCity          string `json:"receiverCity" gorm:"receiver_city"`                    // 城市
	ReceiverRegion        string `json:"receiverRegion" gorm:"receiver_region"`                // 区
	ReceiverDetailAddress string `json:"receiverDetailAddress" gorm:"receiver_detail_address"` // 详细地址
	Note                  string `json:"note" gorm:"note"`                                     // 订单备注

	ConfirmStatus  int64      `json:"confirmStatus" gorm:"confirm_status"`   // 确认收货状态：0->未确认；1->已确认
	DeleteStatus   int64      `json:"deleteStatus" gorm:"delete_status"`     // 删除状态：0->未删除；1->已删除
	UseIntegration int64      `json:"useIntegration" gorm:"use_integration"` // 下单时使用的积分
	PaymentTime    *time.Time `json:"paymentTime" gorm:"payment_time"`       // 支付时间
	// 支付返回的数据
	PaymentData     string     `json:"-"  gorm:"payment_data"`
	DeadlinePayment *time.Time `json:"deadlinePayment" json:"deadline_payment"` // 支付倒计时时间
	DeliveryTime    *time.Time `json:"deliveryTime" gorm:"delivery_time"`       // 发货时间
	DeliveryDate    *time.Time `json:"deliveryDate" gorm:"delivery_date"`       // 预估发货时间
	ReceiveTime     *time.Time `json:"receiveTime" gorm:"receive_time"`         // 确认收货时间
	CommentTime     *time.Time `json:"commentTime" gorm:"comment_time"`         // 评价时间
	ModifyTime      *time.Time `json:"modifyTime" gorm:"modify_time"`           // 修改时间
	MemberCom       int        `json:"memberCom" gorm:"member_com"`             // 用户标识（0 -> 未读， 1 -> 已读）
}

/**
 * 生成18位订单编号:8位日期+2位平台号码+2位支付方式+6位以上自增id
 */
//private String generateOrderSn(OmsOrder order) {
//StringBuilder sb = new StringBuilder();
//String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
//String key = REDIS_DATABASE+":"+ REDIS_KEY_ORDER_ID + date;
//Long increment = redisService.incr(key, 1);
//sb.append(date);
//sb.append(String.format("%02d", order.getSourceType()));
//sb.append(String.format("%02d", order.getPayType()));
//String incrementStr = increment.toString();
//if (incrementStr.length() <= 6) {
//sb.append(String.format("%06d", increment));
//} else {
//sb.append(incrementStr);
//}
//return sb.toString();
//}

func (model *OmsOrder) GenerateOrderSn() string {
	nowTime := time.Now()
	snow := utils.Snowflake{
		Timestamp:    nowTime.Unix(),
		Workerid:     model.SourceType,
		Datacenterid: model.PayType,
		Sequence:     1,
	}
	global.Log.Info("打印时间", zap.Any("data", nowTime))
	tempDate := nowTime.Format("20060102")
	str := strings.TrimPrefix(tempDate, "20")
	temp := fmt.Sprintf("%s%d", str, snow.NextVal())
	return temp
}

func (model *OmsOrder) GeneratePaySn() string {
	nowTime := time.Now()
	snow := utils.Snowflake{
		Timestamp:    nowTime.Unix(),
		Workerid:     model.SourceType,
		Datacenterid: model.PayType,
		Sequence:     1,
	}
	global.Log.Info("打印时间", zap.Any("data", nowTime))
	tempDate := nowTime.Format("20060102")
	str := strings.TrimPrefix(tempDate, "20")
	temp := fmt.Sprintf("%s%d", str, snow.NextVal())
	return temp
}

func formatTwo(num int64) string {
	if num > 99 {
		return fmt.Sprintf("%d", num)
	} else {
		return fmt.Sprintf("0%d", num)
	}
}

func formatSix() {

}
